package net.sppan.blog.controller.admin;

import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;

import net.sppan.blog.annotation.RequiresPermissions;
import net.sppan.blog.commons.Constants;
import net.sppan.blog.controller.BaseController;
import net.sppan.blog.model.Role;
import net.sppan.blog.model.User;
import net.sppan.blog.model.UserRole;
import net.sppan.blog.model.base.Condition;
import net.sppan.blog.model.base.Operators;
import net.sppan.blog.utils.WebUtils;
import sun.misc.BASE64Decoder;

import com.baidu.ueditor.PathFormat;
import com.baidu.ueditor.UeditorConfigKit;
import com.baidu.ueditor.define.FileType;
import com.baidu.ueditor.define.State;
import com.jfinal.aop.Clear;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.ehcache.CacheKit;

@RequiresPermissions(key={"admin:sys:user"})
public class AdminUserController extends BaseController{
	/**
	 * 用户列表
	 */
	@RequiresPermissions(key={"admin:sys:user:list"})
	public void list(){
		int pageNumber = getParaToInt("pageNumber", 1);
        int pageSize = getParaToInt("pageSize", 10);
        String search = getPara("search");
        LinkedHashMap<String, String> orderby = new LinkedHashMap<String, String>();
        orderby.put("createdate", "desc");
        Set<Condition> conditions=new HashSet<Condition>();
        if(StrKit.notBlank(search)){
        	conditions.add(new Condition("name", Operators.LIKE, search));
        	setAttr("search", search);
        }
		Page<User> page = User.dao.getPage(pageNumber, pageSize, conditions, orderby);
		setAttr("pageList", page);
		render("list.html");
	}
	
	/**
	 * 跳转到表单页面
	 */
	@RequiresPermissions(key={"admin:sys:user:save"})
	public void add_edit(){
		Integer id = getParaToInt("id");
		if(id != null){
			User user = User.dao.findById(id);
			setAttr("user", user);
			Role myRole = Role.dao.findRoleByUserId(id);
			setAttr("myRole", myRole);
		}
		List<Role> roles = Role.dao.getAllList();
		setAttr("roles", roles);
		render("form.html");
	}
	/**
	 * 新增-更新用户
	 */
	@RequiresPermissions(key={"admin:sys:user:save"})
	public void save_update(){
		User user = getModel(User.class);
		user.setCreatedate(new Date());
		Integer roleId = getParaToInt("role");
		boolean isSuccess = false;
		if(user.getId() == null){
			isSuccess = user.save();
			if(isSuccess){
				Role.dao.updateRoleByUserId(roleId,user.getId());
				renderJson(isSuccess,"新增成功");
			}else{
				renderJson(isSuccess,"新增失败");
			}
		}else{
			isSuccess = user.update();
			Role.dao.updateRoleByUserId(roleId,user.getId());
			renderJson(isSuccess,"编辑成功");
		}
	}
	
	/**
	 * 删除用户
	 */
	@RequiresPermissions(key={"admin:sys:user:delete"})
	public void delete(){
		Integer id = getParaToInt("id");
		User user = User.dao.findById(id);
		boolean isSuccess  = false;
		if(1 ==user.getId()){
			renderJson(isSuccess,"超级管理员不能删除");
		}else{
			Integer count = UserRole.dao.deleteByUserId(id);
			if (count != null && count >= 0) {
				isSuccess = User.dao.deleteById(id);
				renderJson(isSuccess,"删除成功");
			}else{
				renderJson(isSuccess,"删除失败");
			}
		}
	}
	
	/**
	 * 修改用户密码跳转
	 */
	@RequiresPermissions(key={"admin:sys:user:save"})
	public void change_password(){
		Integer id = getParaToInt("id");
		User user = User.dao.findById(id);
		setAttr("user", user);
		render("change_password.html");
	}
	
	/**
	 * 修改用户密码跳转
	 */
	@RequiresPermissions(key={"admin:sys:user:save"})
	public void change_password_update(){
		Integer id = getParaToInt("id");
		String password1 = getPara("password1");
		String password2 = getPara("password2");
		if(StrKit.isBlank(password1) || StrKit.isBlank(password2) || !password1.equals(password2)){
			renderJson(false, "密码为空或者两次输入的密码不一致");
		}else{
			User user = User.dao.findById(id);
			user.setPwd(WebUtils.pwdEncode(password1));
			user.update();
			renderJson(true, "密码修改成功");
		}
	}
	
	/**
	 * 跳转到修改自己信息表单页面
	 */
	@Clear
	public void change_info(){
		User user = WebUtils.currentUser(getRequest(), getResponse());
		user = User.dao.findById(user.getId());
		setAttr("user", user);
		render("change_info.html");
	}
	
	/**
	 * 修改自己信息
	 */
	@Clear
	public void change_info_update(){
		//获取当前登录用户
		User user = WebUtils.currentUser(getRequest(), getResponse());
		Integer id = user.getId();
		
		user = getModel(User.class);
		//设置要修改的用户ID为当前登录用户，防止通过改表单提交请求来修改其他用户信息
		user.setId(id);
		
		String password1 = getPara("password1");
		String password2 = getPara("password2");
		if(StrKit.notBlank(password1) && StrKit.notBlank(password2) && password1.equals(password2)){
			if(password1.length() < 6 || password1.length() > 16){
				renderJson(false, "密码位数不正确，最少6位最多16位");
				return;
			}else{
				user.setPwd(WebUtils.pwdEncode(password1));
			}
		}
		boolean isSuccess = user.update();
		if(isSuccess){
			renderJson(true, "信息修改成功");
		}else{
			renderJson(false, "信息修改失败");
		}
	}
	
	@Clear
	public void avatar(){
		render("avatar.html");
	}
	
	@Clear
	public void avatar_update(){
		String para = getPara("data");
		if(StrKit.isBlank(para)){
			renderJson(false, "请选择需要上传的头像文件");
			return;
		}
		User user = WebUtils.currentUser(getRequest(), getResponse());
		if(user == null || user.getId() == null){
			renderJson(false, "请登录以后再尝试修改头像");
			return;
		}
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			String suffix = FileType.getSuffix("JPG");
			String[] split = para.split(",");
			byte[] bs = decoder.decodeBuffer(split[1]);
			String savePath = PathFormat.parse("/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", "upfile");
			savePath = savePath + suffix;
			State storageState = UeditorConfigKit.getFileManager().saveFile(bs, PathKit.getWebRootPath(), savePath);
			user = User.dao.findById(user.getId());
			user.setIcon(savePath);
			boolean update = user.update();
			//刷新当前登录用户的session数据，才能让修改的图片重新加载出来(注意类型key的类型必须要是long 不然无法移除)
			CacheKit.remove(Constants.CacheName.session.get(), Long.valueOf(user.getId()));
			if(update && storageState.isSuccess()){
				renderJson(true,"修改头像成功");
			}else{
				renderJson(true,"修改头像失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			renderJson(false, "文件上传出现异常" + e.getMessage());
		}
	}
	
}
